<template>
  <v-layout type="main">
    <!-- <p class="page-title">模型训练</p> -->

    <div class="task-box">
      <drawer-box class="infinite-list" @unfold="unfoldChange" :key="forceRerenderKey">
        <template slot="add">
          <div class="infinite-search">
            <el-input prefix-icon="el-icon-search" v-model="Pagedata.name" class="search" placeholder="请输入内容"
              @input="getData" />
            <a href="javascript:;" class="add el-icon-plus" @click="$router.push({ path: '/gameTask/detail' })">新增</a>
          </div>
        </template>
        <div class="utils">
          <span><el-checkbox v-model="allChecked" />模型训练列表</span>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              排序<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-plus">名称排序</el-dropdown-item>
              <el-dropdown-item icon="el-icon-circle-plus">时间排序</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <template v-if="!isCollapse">
          <div :class="['infinite-item', { 'is-active': item.id === detailData.id }]" v-for="item in taskList"
            :key="item.id" @click="handleChange(item)">
            <!-- <div class="title" @click="$router.push({ path: '/task/code', query: { id: item.id } })> -->
            <div class="infinite-item-left">
              <el-checkbox v-model="item.checked" />
            </div>
            <div class="infinte-item-right">
              <div class="title">
                {{ item.name }}
              </div>
              <div class="item">
                <el-tag effect="dark" size="mini">{{ item.create_user && item.create_user.nick_name }}</el-tag>
                <el-tag type="info" effect="dark" size="mini">{{ item.create_time }}</el-tag>
              </div>
              <div class="item desc">{{ item.desc }} </div>
            </div>
          </div>
        </template>

        <template v-else>
          <el-table :data="taskList" stripe style="width: 100%" class="drawer-box-table">
            <el-table-column prop="name" label="名称">
              <template slot-scope="scope">
                <span @click="tableItemHandler(scope.row)" style="cursor: pointer;">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_user.nick_name" label="创建人"></el-table-column>
            <el-table-column label="描述">
              <template slot-scope="scope">
                {{ scope.row.desc }}
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间"></el-table-column>
            <el-table-column prop="update_time" label="更新时间"></el-table-column>
          </el-table>
        </template>
      </drawer-box>

      <div class="task-container">
        <div class="detail-box" v-if="version !== null">
          <!-- <div class="pic">
            <img src="@/assets/img/notebook2.png" alt="">
          </div> -->
          <div class="word">
            <h3 class="title">
              {{ detailData.name }} <i class="el-icon-edit-outline alick-btn-edit" @click="updateBase" />
              <!-- <span>状态：<strong
                  :class="['alick-layout-status', version.status]">{{ statusMap[version.status]}}</strong></span> -->
              <el-button class="back" type="text" icon="el-icon-right" @click="$router.push({ path: '/gameTask' })" />
            </h3>
            <p class="hint">{{ detailData.desc }}</p>

            <div class="alick-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="start" v-show="version.status == 'terminated'">启动</a>
              <a class="handle-btn" href="javascript:;" @click="goToLink" v-show="version.status == 'running'">打开仿真前端</a>
              <a class="handle-btn" href="javascript:;" @click="stop" v-show="version.status != 'terminated'">停止</a>
              <el-popover placement="bottom-end" width="80" trigger="hover">
                <div class="alick-popover-handle-btns">
                  <a class="handle-btn" href="javascript:;" @click="exportModel">导出模型</a>
                  <a class="handle-btn" href="javascript:;" @click="addVersion">新增版本</a>
                </div>
                <a class="handle-btn" href="javascript:;" slot="reference">更多</a>
              </el-popover>

            </div>
          </div>
        </div>
        <div>
          <div class="select-ver clearfix">
            <span class="label">版本</span>
            <el-select class="select" v-model="select_version" value-key="id" @change="versionChange">
              <el-option v-for="item in versionOptions" :value="item" :label="item.version" :key="item.id">
              </el-option>
            </el-select>

          </div>
          <!-- <p class="commit-info">
            <strong>提交信息</strong>
        </p> -->
        </div>

        <el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
          <el-tab-pane :label="e.meta.title" :name="`${e.name}`" v-for="(e, i) in thisRouter" :key="i" />
        </el-tabs>

        <div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">
          <router-view class="content-detail" :detailData="detailData" :version="version" />
        </div>
      </div>
    </div>

    <el-dialog :visible.sync="showUpdateBaseDialog" title="模型训练基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :rules="baseSubmitRules" :model="taskForm" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="taskForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitBase">确定</el-button>
          <el-button class="none-type" @click="cancelBase">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <div v-if="showExportModelDialog">
      <plug-export-model :show_file.sync=showExportModelDialog @infoShow="infoShowExport" :model_id=model_id
        :biz_id=version.id :business_type="4" />
    </div>
  </v-layout>
</template>

<script>
import drawerBox from "@/components/module/drawer-box.vue"
import { getModelBySource } from "@/api/model"
import { mapActions, mapState } from "vuex"
import { getGameTaskDetail, putGameTask, getAllGameTaskVersions, startGameTaskVersion, stopGameTaskVersion, getGameTaskVersionDetail } from '@/api/gameTask'
import { domain } from '@/config'
import plugExportModel from '@/components/module/plug-export-model'
export default {
  data() {
    return {
      nowRouter: this.$route.name,
      thisRouter: [],
      // detailData: null,
      taskForm: {},
      select_version: null,
      model_id: null,
      version: null,
      versionOptions: [],
      modelForm: { visibility: 0 },
      baseSubmitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到40个字符" },
        ],
      },
      modelSubmitRules: {
        model_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      showUpdateBaseDialog: false,
      showExportModelDialog: false,
      modelOptions: [],
      model: null,
      source_version_id: this.$route.query.source_version_id,
      podUrl: null,
      forceRerenderKey: 0,
      allChecked: false
    };
  },
  components: {
    plugExportModel,
    drawerBox
  },
  methods: {
    ...mapActions(["getTaskList", "updateDetail"]),
    getData() { },
    forceRerender() {
      this.forceRerenderKey += 1;
    },
    unfoldChange(val) {
      this.$store.commit('GAMETASKUNFOLDCHANGE', val);
    },
    skip() {
      let path = `/gameTask/${this.thisRouter.filter(e => e.name == this.nowRouter)[0].path}`
      if (path == this.$route.path) return
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id,
          source_version_id: this.$route.query.source_version_id,

        }
      })
    },
    tableItemHandler(val) {
      this.updateDetail(val)
      this.unfoldChange(false)

      this.$router.push({
        path: "/gameTask",
        query: {
          id: val.id
        }
      })
      this.forceRerender()
    },
    async getTaskVersions() {
      let ret = await getAllGameTaskVersions({ gameTaskId: this.$route.query.id, type: 1 })
      this.versionOptions = ret.data
      let ve
      if (this.versionOptions.length > 0) {
        ve = this.versionOptions[0]
      }
      console.log("source_version_id", this.source_version_id)
      if (this.source_version_id) {
        for (let i = 0; i < this.versionOptions.length; i++) {
          console.log("source_version_id", this.source_version_id,
            this.versionOptions[i].id
          )
          if (this.source_version_id == this.versionOptions[i].id) {
            ve = this.versionOptions[i]
          }
        }
      }
      let res = await getGameTaskVersionDetail({ id: ve.id })
      this.version = res.data
      this.select_version = res.data
      if (this.version && this.version.id) {
        await this.getVersionDetail()
        this.genUrl()
      }
      this.$forceUpdate();
    },
    async getVersionDetail() {
      let res = await getGameTaskVersionDetail({ id: this.select_version.id })
      this.version = res.data
    },
    versionChange() {
      this.getVersionDetail()
    },
    async handleChange(val) {
      // console.log(val);
      // this.detailData = val;
      this.updateDetail(val)
      this.$router.push({
        path: "/gameTask",
        query: {
          id: val.id
        }
      })
    },
    async getDetail() {
      if (this.$route.query.id) {
        let res = await getGameTaskDetail({ id: this.$route.query.id })
        // this.detailData = res.data
        this.updateDetail(res.data)
        this.taskForm = JSON.parse(JSON.stringify(this.detailData))
      }
    },
    updateBase() {
      this.showUpdateBaseDialog = true
    },

    commitBase() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await putGameTask(this.taskForm);
          if (res && res.data) {
            this.getDetail()
            this.showUpdateBaseDialog = false
          }
        }
      })
    },
    cancelBase() {
      this.showUpdateBaseDialog = false
    },
    addVersion() {
      let query = {
        task_id: this.detailData.id,
      }
      this.$router.push({
        path: '/gameTask/detail',
        query
      })
    },
    async exportModel() {
      if (!this.$route.query.id) return
      let data = {
        source: this.version.id
      }
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id
      }
      this.showExportModelDialog = true
    },



    start() {
      if (this.version) {
        startGameTaskVersion({ id: this.version.id });
      }

    },
    async stop() {
      if (this.version) {
        await stopGameTaskVersion({ id: this.version.id });
        this.getDetail()
        this.$forceUpdate()
      }
    },
    infoShowExport(data) {
      this.showExportModelDialog = data
    },
    goToLink() {
      this.genUrl()
      let path = this.podUrl;
      console.log('path', path)
      if (path) {
        window.open(path, '_blank');
      }
    },
    infoData(data) {
      console.log("infoData", data)
      this.getDetail()
      this.$forceUpdate()
    },
    genUrl() {
      if (this.version.status != 'running' || !this.version.tcp_port_list) {
        return null;
      }
      let tcp_port_list = this.version.tcp_port_list
      let simulationFrontUrl = process.env.VUE_APP_SIMULATION_URL;
      console.log(simulationFrontUrl)
      console.log(domain)
      let port4000List = tcp_port_list.filter(map => map.containerPort == '4000')
      let port4001List = tcp_port_list.filter(map => map.containerPort == '4001')
      if (port4000List.length && port4001List.length) {
        let nodePort4000 = port4000List[0].nodePort;
        let nodePort4001 = port4001List[0].nodePort;
        let endpoint = tcp_port_list[0].endpoint.split(':')[0];
        let url = `${simulationFrontUrl}/#/Menu?IP=${endpoint}&port1=${nodePort4000}&port2=4001&port3=${nodePort4001}`;
        this.podUrl = url;
      }

    }
  },
  computed: mapState({
    taskList: state => state.gameTaskStore.taskList,
    isCollapse: state => state.gameTaskStore.isCollapse,
    detailData: state => state.gameTaskStore.detail,
  }),
  mounted() {
    let temp = this.$router.options.routes.filter(
      e => e.name == 'gameTask' && e.children
    )
    this.thisRouter = temp[0].children.filter(e => !e.meta.hideDetails)

    this.getTaskList()

    this.getDetail();
    this.getTaskVersions();
    this.$EventBus.$on('gameTask', e => {
      console.log(e)
      this.getVersionDetail()
    })
  },
  destroyed() {
    this.$EventBus.$off('task')
  },
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

.task-box {
  display: flex;

  .task-container {
    width: 100%;
    // margin-left: 220px;
    margin-left: 470px;
  }
}
</style>